package org.liu.simpleTank.resource;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.liu.simpleTank.CONSTS;

public class TileImage {
	private static BufferedImage tiles;
	static {
		try {
			Class c = Class.forName("org.liu.simpleTank.resource.TileImage");
			URL tilesUrl = c.getResource("tile.png");
			tiles = ImageIO.read(tilesUrl);
		} catch(Exception e) { e.printStackTrace(); }
	}
	
	private static int TILE_SIZE = 16;
	
	private static int unitToSize(int unit) {
		return unit * TILE_SIZE;
	}
	
	public static Image getTile(int type, int frame) {
		if(type == CONSTS.BRICK)
			return getImage(unitToSize(0), 0, TILE_SIZE, TILE_SIZE);
		if(type == CONSTS.STEEL)
			return getImage(unitToSize(1), 0, TILE_SIZE, TILE_SIZE);
		if(type == CONSTS.GRASS)
			return getImage(unitToSize(2), 0, TILE_SIZE, TILE_SIZE);
		if(type == CONSTS.WATER)
			return getImage(unitToSize(3 + frame % 2), 0, TILE_SIZE, TILE_SIZE);
		return null;
	}
	
	private static Map<Long, Image> cache;
	static {
		cache = new HashMap<Long, Image>();
	}
	
	private static Image getImage(int x, int y, int w, int h) {
		long key = x << 24 | y << 16 | w << 8 | h;
		if(cache.containsKey(Long.valueOf(key)))
			return cache.get(Long.valueOf(key));
		else {
			Image img = tiles.getSubimage(x, y, w, h);
			cache.put(Long.valueOf(key), img);
			return img;
		}
	}
}
